<?php
require_once('base.php');

$maxMegas=30;
$valid_formats = array(' pdf','doc', 'docx', 'odt', 'xsw', 'rtf', 'tex',
						"jpg", "png", "gif", "bmp","jpeg");

$usuario_gmail=array('usu'=>'info.money2u@gmail.com',
					'pwd'=>'defcondos',
					);

function getExtension($str) {
	$i = strrpos($str,".");
	if (!$i) { return ""; } 

	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
	}
function recibeArchivos($arr){
	$name = $arr['name'];
	$size = $arr['size'];
	$tmp =  $arr['tmp_name'];
	$ext = getExtension($name);
	
	//lo renombro a su nombre de verdad
	$trozos=explode('/', $tmp);
	$trozos[ count($trozos)-1 ]=$name;
	$nuevaruta=implode('/', $trozos);

	move_uploaded_file($tmp, $nuevaruta);

	$tmp=$nuevaruta;
	// echo '<br><br>';
	// echo '>>>>>>>Movido a '.$nuevaruta;
	// echo '<br><br>';

	global $maxMegas, $valid_formats;

	if(strlen($name) > 0){
		if ( in_array( strtolower($ext), $valid_formats) ){
			$sizeMB=$size/(1024*1024);
			if ($sizeMB<$maxMegas){
				include('S3_config.php');
				//Rename image name. 
				$actual_image_name = time().".".$ext;
				// if($s3->putObjectFile($tmp, $bucket , $actual_image_name, S3::ACL_PUBLIC_READ) ){	
					// $s3file='http://'.$bucket.'.s3.amazonaws.com/'.$actual_image_name;
					return array('imgSubida'=>1, 
								'nombreOriginal'=>$name,
								'tamañoMB'=>$sizeMB,
								// 'rutaS3'=>$s3file,
								'rutaLocal'=>$tmp);
				// 	}
				// else
				// 	return array('imgSubida'=>0, 'error'=>'S3 Upload Fail');
				}
			else
				throw new Exception('File size too large: '.$sizeMB.'MB (max:'.$maxMegas.' MB)');
			}
		else
			throw new Exception('Invalid file type "'.$ext.'" (valid formats:'.json_encode($valid_formats).')')	;
		}
	}
function enviarCorreoIvan($xpet){
	$from=Base::getEmailEmpresa();
	$to = Base::getEmailEmpresa();
	$subject = Base::getUrlEmpresa().': nueva petición';
	$message = '<html><body>'.
			   json_encode($xpet).
			   '</body></html>';

	$rutas=array();
	foreach ($xpet AS $k=>$v){
		$pos=strpos($k, 'adjunto_docu');
		if ($pos!==false){//3 simbolos igual
			// echo '-------<br>';
			// var_dump($v);
			array_push($rutas, $v['rutaLocal']);
			}
		}
	gmail($to, $subject, $message, $rutas);
	}
function enviarCorreoCliente($xpet){
	$to = $xpet['email'];

	$subject = 'Confirmación de '.Base::getUrlEmpresa();

	$nombre=$xpet['nombre'];
	$url=Base::getUrlEmpresa();

	$message = <<<EOT
<html><body>
<p>Estimado señor $nombre:</p>
<p style="margin-top:1rem">
Le confirmamos que hemos recibido su petición. En breve la estudiaremos y le daremos
respuesta a través de alguno de los medios de contacto que nos ha proporcionado.
</p>
<a href="$url">$url</a>
</body></html>
EOT;
	
	gmail($to, $subject, $message, []);
	}
function gmail($to, $subject, $message, $attachments){
	global $usuario_gmail;

	// date_default_timezone_set('Etc/UTC');
	require_once('PHPMailerAutoload.php');
	//Create a new PHPMailer instance
	$mail = new PHPMailer();
	$mail->isSMTP();
	
	//Enable SMTP debugging
	// 0 = off (for production use)
	// 1 = client messages
	// 2 = client and server messages
	$mail->SMTPDebug = 2;
	
	$mail->Debugoutput = 'html';//Ask for HTML-friendly debug output
	
	$mail->Host = 'smtp.gmail.com';//Set the hostname of the mail server
	$mail->Port = 587;//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
	$mail->SMTPSecure = 'tls';//Set the encryption system to use - ssl (deprecated) or tls
	$mail->SMTPAuth = true;//Whether to use SMTP authentication
	
	$mail->Username = $usuario_gmail['usu'];//Username to use for SMTP authentication - use full email address for gmail
	$mail->Password = $usuario_gmail['pwd'];
	$mail->setFrom( $usuario_gmail['usu'], Base::getUrlEmpresa());
	//Set an alternative reply-to address
	// $mail->addReplyTo('replyto@example.com', 'First Last');
	
	$mail->addAddress($to);
	$mail->Subject = $subject;
	$mail->msgHTML($message);

	for ($i=0; $i<count($attachments); $i++){
		$mail->addAttachment( $attachments[$i] );
		}
	return $mail->send();
	}
////////////////
if($_SERVER['REQUEST_METHOD'] == "POST"){
	$xpet=array();

	if (isset($_FILES)){
		foreach ($_FILES AS $k=>$v){
			$f=recibeArchivos($v);;
			$f['descripcion archivo']=$_POST['desc_'.$k];
			$xpet[$k]=$f;
			}
		}
	//resto datos
	foreach ($_POST AS $k=>$v){
		$xpet[ $k ]=$v;
		}

	// var_dump($xpet);
	enviarCorreoIvan($xpet);
	enviarCorreoCliente($xpet);
	//////////
	header( 'Location: respuesta.php' ) ;
	}
?>